<template>
    <div class="account_manage">
        <div class="content_panel_top">
            <h3 class="panel_title">
                <span>{{ $t('system.userManage') }}</span>
            </h3>
            <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item prop="id">
                            <el-input v-model="form.id" maxlength="19" placeholder="ID"></el-input><!--ID-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="userName">
                            <el-input v-model="form.userName" maxlength="100" :placeholder="$t('system.userName')"></el-input><!--用户名-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="cpId"><!--所属公司-->
                            <el-select v-model="form.cpId" :placeholder="$t('system.companyType')" clearable style="width: 100%;">
                                <el-option v-for="company in companyList" :key="company.id" :value="company.id" :label="company.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item prop="status">
                            <el-select v-model="form.status" clearable :placeholder="$t('common.status')" style="width: 100%"><!--状态-->
                                <el-option key="0" :label="$t('collection.closed')" :value="0"></el-option>
                                <el-option key="1" :label="$t('collection.activated')" :value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item>
                            <el-button @click="onSearch" icon="el-icon-search" type="primary">{{ $t('common.search') }}</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" align="right">
                        <el-button @click="editUser('add')" type="primary">{{ $t('system.addUser') }}</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <div class="data_list">
            <el-table :data="tableData" :max-height="tableMaxHeight" style="width: 100%">
                <el-table-column label="ID" prop="id" min-width="70"></el-table-column>
                <el-table-column :label="$t('system.userName')" prop="username" min-width="150"></el-table-column><!--用户名-->
                <el-table-column :label="$t('system.companyType')" prop="companyName" min-width="150"></el-table-column><!--所属公司-->
                <el-table-column :label="$t('system.appName') + '<' + $t('system.appPackage') + '>'" prop="apps" min-width="250">
                    <template slot-scope="{ row }">
                        <p v-for="item in row.apps">{{ item.name }} <{{ item.packageName }}></p>
                    </template>
                </el-table-column><!--APP名称<包名>-->
                <el-table-column :label="$t('common.remark')" prop="remark" width="160" :show-overflow-tooltip="true"></el-table-column><!--备注-->
                <el-table-column :label="$t('common.createTime')" prop="createTime" min-width="170"><!--创建时间-->
                    <template slot-scope="{ row }">{{ row.createTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                </el-table-column>
                <el-table-column :label="$t('common.updateTime')" prop="updateTime" min-width="170"><!--更新时间-->
                    <template slot-scope="{ row }">{{ row.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                </el-table-column>
                <el-table-column prop="status" :label="$t('common.status')" min-width="100"><!--状态-->
                    <template slot-scope="scope">
                        <el-switch @change="changeStatus(scope.row)" v-model="scope.row.status"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('system.resourceAuth')" min-width="160"><!--资源授权-->
                    <template slot-scope="scope">
                        <el-button @click="getResourceById(scope.row)" :disabled="scope.row.status === false" type="text" size="small">{{ $t('system.bindingResource') }}</el-button><!--绑定资源-->
                    </template>
                </el-table-column>
                <el-table-column :label="$t('common.operation')" min-width="160">
                    <template slot-scope="scope">
                        <el-button @click="editUser('edit',scope.row)" :disabled="scope.row.status === false" type="text" size="small">{{ $t('finance.edit') }}</el-button>
                        <el-button @click="resetPassword(scope.row)" :disabled="scope.row.status === false" type="text" size="small">{{ $t('system.resetPassword') }}</el-button>
                    </template>
                </el-table-column>
            </el-table><!--end table-->
        </div>
        <div class="data_page">
            <pagination @pageChange="pageChange" :page="page"><!--分页组件--></pagination>
        </div>

        <!--编辑用户start-->
        <el-dialog :title="$t('system.companyInfo')" :visible.sync="addDialog.isVisible" width="800px">
            <el-form :model="addDialog.form" :rules="addDialog.rules" ref="addDialog.form" label-position="right" label-width="150px">
                <el-form-item :label="$t('system.userName')" prop="userName"><!--用户名-->
                    <el-input v-model="addDialog.form.userName" :disabled="addDialog.type === 'edit'" type="text" maxlength="100"></el-input>
                </el-form-item>
                <el-form-item :label="$t('system.companyType')" prop="cpId"><!--所属公司-->
                    <el-select v-model="addDialog.form.cpId" :disabled="addDialog.type === 'edit'" style="width: 100%">
                        <el-option v-for="(company,index) in companyList" :key="index" :value="company.id" :label="company.name"></el-option>
                    </el-select>
                </el-form-item>
                <div v-for="(apps, index) in addDialog.form.apps">
                    <el-form-item
                            :label="$t('system.appInfo') + ' ' + (index + 1)"
                            :key="apps.key"
                            :prop="'apps.' + index + '.name'"
                            :rules="{required: true, message: $t('verify.plsInput'), trigger: 'blur'}"
                            style="display: inline-block;width:50%">
                        <el-input v-model="apps.name" :placeholder="$t('system.appName')" maxlength="100" style="width: 100%"></el-input>
                    </el-form-item>
                    <el-form-item
                            :key="apps.key"
                            :prop="'apps.' + index + '.packageName'"
                            :rules="{required: true, message: $t('verify.plsInput'), trigger: 'blur'}"
                            label-width="0px"
                            style="display: inline-block;width:50%">
                        <el-input v-model="apps.packageName" :placeholder="$t('system.appPackage')" maxlength="100" style="width: 70%"></el-input><el-button @click="removeApp(index,apps)" type="danger" icon="el-icon-delete" circle class="mgl-10"></el-button>
                    </el-form-item>
                </div>
                <div class="pdl-150"><el-button @click="addApp">{{ $t('system.addAppInfo') }}</el-button></div>
                <el-form-item :label="$t('common.remark')" prop="remark"><!--备注-->
                    <el-input v-model="addDialog.form.remark" type="textarea" :placeholder="$t('verify.underXWords',{x: 200})" maxlength="200" :rows="3"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="addUserSubmit" type="primary">{{ $t('common.confirm') }}</el-button>
                <el-button @click="addDialog.isVisible = false" type="default">{{ $t('common.cancel') }}</el-button>
            </div>
        </el-dialog>
        <!--新增用户end-->

        <!--绑定资源start-->
        <el-dialog :title="$t('system.bindingResource')" :visible.sync="bindResourceDialogShow" width="500px">
            <el-form class="role_form" :model="roleForm" label-position="top">
                <!--<el-form-item :label="$t('system.companyName')">&lt;!&ndash;公司名称&ndash;&gt;-->
                    <!--<el-input v-model="roleForm.companyName" type="text" :disabled="true"></el-input>-->
                <!--</el-form-item>-->
                <el-form-item :label="$t('system.resourceList')"><!--资源列表-->
                    <el-tree ref="tree" :data="resourceList" show-checkbox node-key="id" :default-checked-keys="roleForm.checkedRes" :props="defaultProps">
                    </el-tree>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="bindResConfirm" type="primary">{{ $t('system.binding') }}</el-button><!--绑定-->
                <el-button @click="bindResourceDialogShow = false" type="default">{{ $t('common.cancel') }}</el-button>
            </div>
        </el-dialog>
        <!--绑定资源end-->
    </div>
</template>

<script>
    import Pagination from '@/components/pagination';
    import mixin from '@/service/mixin';
    import AlertDialog from '@/components/alert-dialog';

    export default {
        name: 'systemAccount',
        components: {
            Pagination,
            AlertDialog
        },
        mixins: [mixin],
        data() {
            return {
                tableData: [],
                companyList: [],
                form: {
                    id: '',
                    userName: '',
                    cpId: '',
                    status: '',
                },
                rules: {
                    id: [],
                    userName: [],
                    cpId: [],
                    status: [],
                },
                addDialog: {
                    type: '',
                    id: '',
                    isVisible: false,
                    form: {
                        userName: '',
                        cpId: '',
                        apps: [{name: '', packageName: '',id: ''}],
                        remark: '',
                    },
                    rules: {
                        cpId: [
                            {required: true, message: this.$t('verify.plsChoose'), trigger: 'change'}
                        ],
                        userName: [
                            {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                            {pattern: /^[A-Za-z0-9]+$/, message: this.$t('verify.plsInputNumberAlp'), trigger: 'blur'}
                        ],
                        remark: [],
                    },
                },
                roleForm: {
                    //companyName: '',
                    roleId: '',
                    checkedRes: [],
                    userName: '',
                    id: ''
                },
                resourceList: [],
                bindResourceDialogShow: false,
                deleteApp: [],
            };
        },
        computed: {
            defaultProps() {
                return {
                    children: 'children',
                    label: this.$i18n.locale === 'zhCN' ? 'cnName' : 'name',
                };
            },
        },
        methods: {
            getTableData(page = this.page) {
                const form = this.form;
                const params = {
                    username: form.userName,
                    id: form.id,
                    cpId: form.cpId,
                    status: form.status,
                    pageNum: page.currentPage,
                    pageSize: this.page.pageSize
                };
                this.$api.systemManage.getUserCompanyList(params).then((res) => {
                    const {status, data, error} = res;
                    if ('1' === status && error === '00000000') {
                        this.tableData = data.userList || [];
                        this.tableData.forEach((item) => {
                            item.status = +item.status === 1;
                        });
                        this.setPage({total: data.total,page: page.currentPage}, this.page);
                        this.tableMaxHeight = window.document.body.clientHeight - 200;
                    }
                });
            },
            onSearch() {
                this.page.currentPage = 1;
                this.getTableData();
            },
            // 添加APP信息
            addApp() {
                this.addDialog.form.apps.push({
                    name: '',
                    packageName: '',
                });
            },
            // 删除APP信息
            removeApp(index,apps) {
                if(this.addDialog.form.apps.length <= 1){
                    this.$message.error(this.$t('system.leastOneApp'));
                    return
                }
                this.addDialog.form.apps.splice(index,1);
                if(apps.id && apps.id !== '') {
                    this.deleteApp.push({id: apps.id});
                    console.log(this.deleteApp);
                }

            },
            editUser(type,row) {
                this.addDialog.type = type;
                if(type === 'add') {
                    this.addDialog.isVisible = true;
                    this.addDialog.form.cpId = '';
                    this.addDialog.form.userName = '';
                    this.addDialog.form.apps = [{name: '', packageName: '',id: ''}];
                    this.addDialog.form.remark = '';
                    this.$nextTick( () => {
                        this.$refs['addDialog.form'].clearValidate();
                    });
                }
                if(type === 'edit') {
                    this.addDialog.id = row.id;
                    this.addDialog.isVisible = true;
                    this.addDialog.form.cpId = row.companyId;
                    this.addDialog.form.userName = row.username;
                    this.addDialog.form.apps = (JSON.parse(JSON.stringify(row.apps))).reverse();
                    this.addDialog.form.remark = row.remark;
                    this.deleteApp = [];
                    this.$nextTick( () => {
                        this.$refs['addDialog.form'].clearValidate();
                    });
                }
            },
            addUserSubmit() {
                const form = this.addDialog.form;
                const type = this.addDialog.type;
                this.$refs['addDialog.form'].validate((value) => {
                    if (value) {
                        const params = JSON.parse(JSON.stringify(form));
                        if(type === 'add') {
                            this.$api.systemManage.addCompanyUser(params).then((res) => {
                                const { status, error, msg } = res;
                                if ('1' === status && '00000000' === error) {
                                    this.addDialog.isVisible = false;
                                    this.onSearch();
                                    this.$message.success(this.$t('common.successfulOperation'));
                                }
                                else if('70000107' === error) {
                                    this.$message.error(this.$t('system.nameIsExist'));
                                }
                                else {
                                    this.$message.error(msg || this.$t('common.failedOperation'));
                                }
                            });
                        }
                        if(type === 'edit') {
                            params.userId = this.addDialog.id;
                            params.apps = form.apps.concat(this.deleteApp);
                            this.$api.systemManage.editCompanyUser(params).then((res) => {
                                const { status, error, msg } = res;
                                if ('1' === status && '00000000' === error) {
                                    this.addDialog.isVisible = false;
                                    this.$message.success(this.$t('common.successfulOperation'));
                                }
                                else {
                                    this.$message.error(msg || this.$t('common.failedOperation'));
                                }
                                this.getTableData();
                            });
                        }
                    }
                });
            },
            // 获取资源列表
            getResourceList() {
                this.roleForm.checkedRes = [];
                this.$api.systemManage.getResourceTree().then((res) => {
                    const {status, data, error} = res;
                    if ('1' === status && error === '00000000' && data) {
                       //去掉指标中心、结算中心、公司管理、角色管理、APP初始化配置
                      //  this.resourceList = data
                       this.resourceList = data.filter(item=>{
                          if (item.path === '/authority') {
                            item.children = item.children.filter(subItem=> {
                              return subItem.path !== '/system-authority/system-admin-company' && subItem.path !== '/system-authority/system-admin-resource' && subItem.path !== '/system-authority/app-initial-configuration'
                            })
                          }
                          return item.path !== '/quotaCenter' && item.path !== '/settlementCenter'
                        })
                    }
                });
            },
            // 获取绑定资源
            getResourceById(row) {
                //this.roleForm.companyName = row.name;
                this.roleForm.roleId = row.roleId;
                this.roleForm.userName = row.username;
                this.roleForm.id = row.id;
                const params = {
                    roleId: row.roleId
                };
                this.$api.systemManage.getResourceIdListByRoleId(params).then((res) => {
                    const {status, data, error, msg} = res;
                    if ('1' === status && error === '00000000') {
                        this.bindResourceDialogShow = true;
                        if (data instanceof Array) {
                            this.roleForm.checkedRes = Object.assign([], data);
                            this.$nextTick(() => {
                                // 设置选中项
                                this.$refs.tree.setCheckedKeys(this.roleForm.checkedRes);
                            });
                        }
                    }
                    else {
                        this.$message.error(msg);
                    }
                });
            },
            // 确认绑定资源
            bindResConfirm() {
                const params = {
                    roleId: this.roleForm.roleId,
                    resourceIdList: this.$refs.tree.getCheckedKeys()
                };
                if (this.roleForm.userName === 'Pesopop') { // 特殊处理Pesopop，分配指标中心相关资源
                  params.resourceIdList = [...params.resourceIdList, 365, 366, 367, 370]
                }
                this.$api.systemManage.editRoleResource(params).then((res) => {
                    const {status, error, msg} = res;
                    if ('1' === status && error === '00000000') {
                        this.bindResourceDialogShow = false;
                        this.$message.success(this.$t('common.successfulOperation'));
                        this.getRoleListByDomain();
                    }
                    else {
                        this.$message.error(msg || this.$t('common.failedOperation'));
                    }
                    this.getTableData();
                });
            },
            resetPassword(row) {
                this.$confirm(this.$t('system.isResetPsw',{x: row.username}), '', {
                    confirmButtonText: this.$t('common.confirm'),
                    cancelButtonText: this.$t('common.cancel'),
                    type: 'warning'
                }).then(() => {
                    const params = {
                        id: row.id
                    };
                    this.$api.systemManage.resetPassword(params).then((res) => {
                        const {status, error, msg} = res;
                        if ('1' === status && error === '00000000') {
                            this.onSearch();
                            this.$message.success(this.$t('common.successfulOperation'));
                        }
                        else {
                            this.$message.error(msg || this.$t('common.failedOperation'));
                        }
                    });
                }).catch(() => {
                });
            },
            // 状态开关
            changeStatus(row) {
                this.$confirm(row.status === true ? this.$t('system.isOpenUser') : this.$t('system.isCloseUser'), '', {
                    confirmButtonText: this.$t('common.confirm'),
                    cancelButtonText: this.$t('common.cancel'),
                    type: 'warning'
                }).then(() => {
                    this.operStatus(row);
                }).catch(() => {
                    row.status = !row.status;
                });
            },
            // 状态操作
            operStatus(row) {
                const params = {
                    id: row.id
                };
                this.$api.systemManage.deleteUser(params).then((res) => {
                    const { status, error, msg } = res;
                    if ('1' === status && '00000000' === error) {
                        this.onSearch();
                        this.$message.success(this.$t('common.successfulOperation'));
                    }
                    else {
                        this.getTableData();
                        this.$message.error(msg || this.$t('common.failedOperation'));
                    }
                });
            },
            getCompanyList() {
                const params = {
                    status: 1,
                    pageNum: 1,
                    pageSize: 100000
                };
                this.$api.systemManage.getCompanyList(params).then((res) => {
                    const {status, data, error} = res;
                    if ('1' === status && error === '00000000') {
                        this.companyList = data.companyList;
                    }
                });
            },
            getRoleListByDomain() {
                const params = {
                    currentUserId: this.roleForm.id
                };
                this.$api.systemManage.getrolelistbydomain(params).then((res) => {
                    const {status, data, error} = res;
                    if ('1' === status && error === '00000000' && data.roleList instanceof Array) {
                      if (data.roleList.length < 1) {
                        setTimeout(() => {
                          this.$confirm(
                            this.$t('common.createRoleTipsText', {x: this.roleForm.userName}),
                            this.$t('common.createRole'),
                            {
                              cancelButtonText: this.$t('common.cancel'),
                              confirmButtonText: this.$t('common.create'),
                              type: 'warning'
                            }
                          )
                            .then(() => {
                              this.initializeRole();
                            })
                            .catch(() => {
                            });
                        }, 300);
                      }
                    }
                });
            },
            //初始化角色
            initializeRole() {
              const params = {
                  currentUserId: this.roleForm.id
              };
              this.$api.systemManage.initrolebydomain(params).then((res) => {
                  const {status, error} = res;
                  if ('1' === status && error === '00000000') {
                      this.$message.success(this.$t('common.successfulOperation'));
                  }
              });
            }
        },
        created() {
            this.onSearch();
            this.getCompanyList();
            this.getResourceList();
        }
    };
</script>

<style lang="scss" scoped>
    .inputPhone {
        width: 265px;
    }

    .search {
        background-color: #fff;
        padding: 22px 40px 0;
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
    }

    .data_list {
        background-color: #fff;
        margin: 16px 24px;
        padding: 10px 16px;
    }

    .btn {
        margin-right: 15px;
    }

    .btn_red {
        /*border-color: #d9415c;*/
        color: #d9415c;
    }

    // .role_form {
    /*padding: 0 16px;*/
    // }

    .account_form_type {
        width: 100%;
    }
    .pdl-150 {
        padding:0 0 25px 150px;
    }
    .mgl-10 {
        margin-left:10px;
    }
</style>
